#pragma once

#include "index.hpp"
#include "util.hpp"
#include <algorithm>
#include <jsoncpp/json/json.h>

namespace ns_search
{
    struct InvertedElemPrint
    {
        uint64_t doc_id; // 文档id
        int weight;      // 权重
        std::vector<std::string> words;
    };

    struct Greater
    {
        bool operator()(const InvertedElemPrint &e1, const InvertedElemPrint &e2)
        {
            return e1.weight > e2.weight;
        }
    };

    class search
    {
    public:
        search() {}
        ~search() {}
        void Initsearch(const std::string &input)
        {
            // 获取或者创建index对象
            index = ns_index::index::GetInstance();
            //std::cout << "创建index对象成功..." << std::endl;
            lg(Info, "%s, %s, %d", "创建index对象成功...", __FILE__, __LINE__);

            // 创建索引
            index->BuildIndex(input);
            //std::cout << "建立索引成功..." << std::endl;
            lg(Info, "%s, %s, %d", "建立索引成功...", __FILE__, __LINE__);
        }

        void Search(const std::string &query, std::string *jsonstr)
        {
            // 1、对query进行分词
            std::vector<std::string> words;
            Util::JiebaUtil::Cutforstring(query, &words);

            // 2、查到倒排索引
            // ns_index::InvertedList invertedlist_all;
            std::vector<InvertedElemPrint> invertedlist_all;

            // 这个map用来进行去重
            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map;
            for (std::string word : words)
            {
                boost::to_lower(word);
                ns_index::InvertedList *invertedlist = index->GetInvertedList(word);
                if (nullptr == invertedlist)
                {
                    std::cout << "get invertedlist failed about " << word << std::endl;
                    continue;
                }

                // invertedlist_all.insert(invertedlist_all.end(), invertedlist->begin(), invertedlist->end());
                // 去重
                for (const auto &item : *invertedlist)
                {
                    auto &elem = tokens_map[item.doc_id];
                    elem.doc_id = item.doc_id;
                    elem.weight += item.weight;
                    elem.words.push_back(item.key_word);
                }
            }
            for (const auto &item : tokens_map)
            {
                invertedlist_all.push_back(std::move(item.second));
            }

            // 3、根据权重值降序排序
            std::sort(invertedlist_all.begin(), invertedlist_all.end(), Greater());

            // 4、序列化
            Json::Value root;
            for (auto &item : invertedlist_all)
            {
                ns_index::DocInfo *doc = index->GetForwardIndex(item.doc_id);
                if (nullptr == doc)
                {
                    std::cout << "get forwardindex failed" << std::endl;
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->desc, item.words[0]);
                elem["url"] = doc->url;
                // elem["weight"] = item.weight;
                // elem["doc_id"] = (int)item.doc_id;

                root.append(elem);
            }
            // Json::StyledWriter writer;
            Json::FastWriter writer;
            *jsonstr = writer.write(root);
        }

    private:
        std::string GetDesc(const std::string &content, const std::string &key_word)
        {
            // 找到Word关键字在content中首次出现的位置，往前找50个字节（如果没有就从开始位置开始），往后找100个字节（如果不足100字节就把剩下的全拿到）
            auto iter = std::search(content.begin(), content.end(), key_word.begin(), key_word.end(), [](int x, int y)
                                    { return (std::tolower(x) == std::tolower(y)); });

            if (iter == content.end())
            {
                return "None1";
            }
            int pos = std::distance(content.begin(), iter);

            int prev_step = 50;
            int next_step = 100;
            int start = 0;
            int end = content.size() - 1;

            if (pos - prev_step > start)
            {
                start = pos - prev_step;
            }
            if (pos + next_step < end)
            {
                end = pos + next_step;
            }
            if (start > end)
            {
                return "None2";
            }
            return content.substr(start, end - start);
        }

    private:
        ns_index::index *index;
    };
};